﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using FrameWork;
using Slja.Model;
using FrameWork.web.Web;
using FrameWork.BasePage;

namespace Slja.WEB.Web.Tool
{
    public partial class Linkman : Page//SljaBasePage
    {
        List<Model.EnumBasicDataModel> _TypeList = null;
        protected List<Model.EnumBasicDataModel> TypeList
        {
            get
            {
                if (_TypeList == null)
                {
                    _TypeList = new BLL.EnumBasicDataBLL().GetLinkmanType();
                    EnumBasicDataModel md1 = new EnumBasicDataModel();
                    EnumBasicDataModel md2 = new EnumBasicDataModel();
                    md1.Code = "0"; md1.Text = "本公司员工";
                    md2.Code = ""; md2.Text = "（选择）";
                    _TypeList.Insert(0, md2);
                    _TypeList.Insert(1, md1);
                }
                return _TypeList;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            btnQuery.Click += new EventHandler(btnQuery_Click);
            GridView1.RowDataBound += new GridViewRowEventHandler(GridView1_RowDataBound);
            //GridView1.RowCommand += new GridViewCommandEventHandler(GridView1_RowCommand);
            GridView1.RowEditing += new GridViewEditEventHandler(GridView1_RowEditing);
            GridView1.RowUpdating += new GridViewUpdateEventHandler(GridView1_RowUpdating);
            GridView1.RowDeleting += new GridViewDeleteEventHandler(GridView1_RowDeleting);
            GridView1.RowCancelingEdit += new GridViewCancelEditEventHandler(GridView1_RowCancelingEdit);
            lbnAdd.Click += new EventHandler(lbnAdd_Click);
            if (!IsPostBack)
            {
                BindLinkmanType(drpType);
                BindClient();
                BindGridView();
            }
        }

        void lbnAdd_Click(object sender, EventArgs e)
        {
            GridView1.EditIndex = 0;
            BindGridView(true);
        }

        void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string TableName = e.Keys[0].ToString();
            int ID = (int)e.Keys[1];
            if (TableName.ToUpper() == "BIZ_LINKMAN")
            {
                SaveLinkman(e);   
            }
            else if (TableName.ToUpper() == "SYS_USER")
            {
                //不允许修改
            }
            GridView1.EditIndex = -1;
            BindGridView(false);
        }
        private void SaveSysUser(GridViewUpdateEventArgs e)
        {
            int ID = (int)e.Keys[1];
            Model.Platform.UserModel model = new Model.Platform.UserModel();
           // model.Tablename = e.Keys[0].ToString();
            model.U_CName = (e.NewValues["FullName"] ?? "").ToString();
            model.U_UserNO = (e.NewValues["Pinyin"] ?? "").ToString();
            model.U_EName = (e.NewValues["ShortPY"] ?? "").ToString();
            model.U_Sex = int.Parse(((DropDownList)GridView1.Rows[e.RowIndex].FindControl("drpGender")).Text);
            model.U_MobileNo = (e.NewValues["MobileTel"] ?? "").ToString();
            //model.Type = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("drpType")).Text;
            model.U_Email = (e.NewValues["Email"] ?? "").ToString();
            model.U_Extension = (e.NewValues["JobTel"] ?? "").ToString();
            model.U_Remark = (e.NewValues["Memo"] ?? "").ToString();
            model.UserID = ID;
            BLL.Platform.UserBLL ubll = new BLL.Platform.UserBLL();
            ubll.Update(model);
        }
        private void SaveLinkman(GridViewUpdateEventArgs e)
        {
            int ID = (int)e.Keys[1];
            Model.LinkManModel model = new LinkManModel();
            model.Tablename = e.Keys[0].ToString();
            model.FullName = (e.NewValues["FullName"] ?? "").ToString();
            model.Pinyin = (e.NewValues["Pinyin"] ?? "").ToString();
            model.ShortPY = (e.NewValues["ShortPY"] ?? "").ToString();
            model.Gender = int.Parse(((DropDownList)GridView1.Rows[e.RowIndex].FindControl("drpGender")).Text);
            model.MobileTel = (e.NewValues["MobileTel"] ?? "").ToString();
            model.Type = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("drpType")).Text;
            model.Email = (e.NewValues["Email"] ?? "").ToString();
            model.JobTel = (e.NewValues["JobTel"] ?? "").ToString();
            model.Memo = (e.NewValues["Memo"] ?? "").ToString();

            string tip;
            if (!ValidInput(model, out tip))
            {
                WebCommon.AlertMsg(Page, tip);
                return;
            }

            BLL.LinkManBLL link = new BLL.LinkManBLL();
            //新增
            if (ID == 0)
            {
                link.Add(model);
                WebCommon.AlertMsg(Page, "保存成功！");
            }
            //更新
            else
            {
                model.ID = ID;
                link.Update(model);
                WebCommon.AlertMsg(Page, "更新成功！");
            }  
        }
        bool ValidInput(Model.LinkManModel model, out string tip)
        {
            tip = "";
            if (string.IsNullOrEmpty(model.FullName))
            {
                tip = "姓名不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(model.Pinyin))
            {
                tip = "请输入姓名的拼音";
                return false;
            }
            if (string.IsNullOrEmpty(model.ShortPY))
            {
                tip = "请输入拼音的缩写";
                return false;
            }
            if (string.IsNullOrEmpty(model.Type))
            {
                tip = "请选择联系人类别";
                return false;
            }

            return true;
        }
        void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            BindGridView();
        }

        void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            BLL.LinkManBLL linkman = new BLL.LinkManBLL();
            string TableName = e.Keys[0].ToString();
            int ID = (int)e.Keys[1];
            if (TableName.ToUpper() != "SYS_USER" && ID > 0)
            {
                linkman.Delete(ID);//删除

                //重新绑定
                GridView1.EditIndex = -1;
                BindGridView(false);
                WebCommon.AlertMsg(Page, "删除成功！");
            }
        }

        void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            BindGridView();
        }

        void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Model.LinkManModel dataitem = (Model.LinkManModel)e.Row.DataItem;
                if (e.Row.RowState == DataControlRowState.Normal
                    || e.Row.RowState == DataControlRowState.Alternate)
                {

                    Literal ltr;
                    //性别
                    ltr = e.Row.FindControl("ltrGender") as Literal;
                    if (ltr != null)
                    {
                        ltr.Text = dataitem.Gender.Value == 0 ? "女" : "男";
                    }
                    //类型
                    ltr = e.Row.FindControl("ltrType") as Literal;
                    if (ltr != null)
                    {

                        EnumBasicDataModel model = TypeList.Find(delegate(EnumBasicDataModel md) { return md.Code == dataitem.Type; });
                        ltr.Text = model.Text;
                    }
                    //编辑 按钮
                    LinkButton lbnEdit = e.Row.Cells[e.Row.Cells.Count - 1].FindControl("ctl00") as LinkButton;
                    if (lbnEdit != null)
                    {
                        if (dataitem.Tablename.ToUpper() == "SYS_USER")
                        {
                            lbnEdit.Enabled = false;
                        }                      
                    }
                    //删除 按钮
                    LinkButton lbn = e.Row.Cells[e.Row.Cells.Count - 1].FindControl("ctl01") as LinkButton;
                    if (lbn != null)
                    {
                        if (dataitem.Tablename.ToUpper() == "SYS_USER")
                        {
                            lbn.Enabled = false;
                        }
                        else
                        {
                            lbn.OnClientClick = "return confirm('真的要删除此行么？');";
                        }
                    }
                }
                else if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
                {

                    //类型
                    DropDownList drp = e.Row.FindControl("drpType") as DropDownList;
                    if (drp != null)
                    {
                        BindLinkmanType(drp);
                        drp.Items.Remove(new ListItem("本公司员工", "0"));
                        drp.SelectedValue = dataitem.Type;
                    }
                    //性别
                    drp = e.Row.FindControl("drpGender") as DropDownList;
                    if (drp != null)
                    {
                        drp.SelectedValue = dataitem.Gender.Value.ToString();
                    }

                    //保存 按钮
                    LinkButton lbn = e.Row.Cells[e.Row.Cells.Count - 1].Controls[0] as LinkButton;
                    if (lbn != null)
                    {
                        if (dataitem.Tablename.ToUpper() != "SYS_USER" && dataitem.ID == 0)
                        {
                            lbn.Text = "保存";
                        }
                    }
                }
            }
        }

        void btnQuery_Click(object sender, EventArgs e)
        {
            BindGridView();
        }

        protected void BindLinkmanType(DropDownList drp)
        {

            if (drp != null)
            {
                drp.DataValueField = "Code";
                drp.DataTextField = "Text";
                drp.DataSource = TypeList;
                drp.DataBind();
                //drp.Items.Insert(0, new ListItem("（选择）", ""));
                //drp.Items.Insert(1, new ListItem("本公司员工", "0"));
            }
        }
        private void BindClient()
        {
            drpCompany.DataValueField = "ClientID";
            drpCompany.DataTextField = "ClientName";
            drpCompany.DataSource = new BLL.ClientBLL().GetModelList("");
            drpCompany.DataBind();
            drpCompany.Items.Insert(0, new ListItem("（选择）", ""));

        }
        private void BindGridView()
        {
            BindGridView(false);
        }
        private void BindGridView(bool AddNewBlankRow)
        {
            string strWhere = GetSqlWhere();
            List<Model.LinkManModel> linkmans = new BLL.LinkManBLL().GetModelList(strWhere, true);
            if (AddNewBlankRow)
            {
                Model.LinkManModel model = new LinkManModel();
                model.Tablename = "biz_LinkMan";
                model.Type = "102";
                model.ID = 0;
                model.Gender = 0;

                linkmans.Insert(0, model);
            }
            GridView1.DataSource = linkmans;
            GridView1.DataKeyNames = new string[] { "Tablename", "ID" };
            GridView1.DataBind();
        }

        private string GetSqlWhere()
        {
            StringBuilder sb = new StringBuilder(" 1=1 ");
            if (drpType.SelectedValue != "")
            {
                sb.Append(" and [type]='" + drpType.SelectedValue + "'");
            }
            if (drpCompany.SelectedValue != "")
            {
                sb.Append(" and [Company]='" + drpCompany.Text + "'");
            }
            if (tbxKeyword.Text.Trim() != "")
            {
                sb.Append(" and " + drpQueryType.SelectedValue + " like '%" + Common.querySQL(tbxKeyword.Text.Trim()) + "%'");
            }
            return sb.ToString();
        }
    }
}